package com.gt.utils;

import org.apache.poi.util.IOUtils;
import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

public class TimeRSAUtils {
    public static final String CHARSET = "UTF-8";
    public static final String RSA_ALGORITHM = "RSA";


    public static Map<String, String> createKeys(int keySize){
        //为RSA算法创建一个KeyPairGenerator对象
        KeyPairGenerator kpg;
        try{
            kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM);
        }catch(NoSuchAlgorithmException e){
            throw new IllegalArgumentException("No such algorithm-->[" + RSA_ALGORITHM + "]");
        }

        //初始化KeyPairGenerator对象,密钥长度
        kpg.initialize(keySize);
        //生成密匙对
        KeyPair keyPair = kpg.generateKeyPair();
        //得到公钥
        Key publicKey = keyPair.getPublic();
        String publicKeyStr = Base64.encodeBase64URLSafeString(publicKey.getEncoded());
        //得到私钥
        Key privateKey = keyPair.getPrivate();
        String privateKeyStr = Base64.encodeBase64URLSafeString(privateKey.getEncoded());
        Map<String, String> keyPairMap = new HashMap<String, String>();
        keyPairMap.put("publicKey", publicKeyStr);
        keyPairMap.put("privateKey", privateKeyStr);

        return keyPairMap;
    }

    /**
     * 得到公钥
     * @param publicKey 密钥字符串（经过base64编码）
     * @throws Exception
     */
    public static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
        //通过X509编码的Key指令获得公钥对象
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
        RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
        return key;
    }

    /**
     * 得到私钥
     * @param privateKey 密钥字符串（经过base64编码）
     * @throws Exception
     */
    public static RSAPrivateKey getPrivateKey(String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
        //通过PKCS#8编码的Key指令获得私钥对象
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
        RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
        return key;
    }

    /**
     * 公钥加密
     * @param data
     * @param publicKey
     * @return
     */
    public static String publicEncrypt(String data, RSAPublicKey publicKey){
        try{
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), publicKey.getModulus().bitLength()));
        }catch(Exception e){
            throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
        }
    }

    /**
     * 私钥解密
     * @param data
     * @param privateKey
     * @return
     */

    public static String privateDecrypt(String data, RSAPrivateKey privateKey){
        try{
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), privateKey.getModulus().bitLength()), CHARSET);
        }catch(Exception e){
            throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
        }
    }

    /**
     * 私钥加密
     * @param data
     * @param privateKey
     * @return
     */

    public static String privateEncrypt(String data, RSAPrivateKey privateKey){
        try{
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), privateKey.getModulus().bitLength()));
        }catch(Exception e){
            throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
        }
    }

    /**
     * 公钥解密
     * @param data
     * @param publicKey
     * @return
     */

    public static String publicDecrypt(String data, RSAPublicKey publicKey){
        try{
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), publicKey.getModulus().bitLength()), CHARSET);
        }catch(Exception e){
            throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
        }
    }

    private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize){
        int maxBlock = 0;
        if(opmode == Cipher.DECRYPT_MODE){
            maxBlock = keySize / 8;
        }else{
            maxBlock = keySize / 8 - 11;
        }
        ByteArrayOutputStream
                out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] buff;
        int i = 0;
        try{
            while(datas.length > offSet){
                if(datas.length-offSet > maxBlock){
                    buff = cipher.doFinal(datas, offSet, maxBlock);
                }else{
                    buff = cipher.doFinal(datas, offSet, datas.length-offSet);
                }
                out.write(buff, 0, buff.length);
                i++;
                offSet = i * maxBlock;
            }
        }catch(Exception e){
            throw new RuntimeException("加解密阀值为["+maxBlock+"]的数据时发生异常", e);
        }
        byte[] resultDatas = out.toByteArray();
        IOUtils.closeQuietly(out);
        return resultDatas;
    }

    public static void main (String[] args) throws Exception {
        String str = "hello world";
//        国通的公私钥
        String gtPublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCb3QKjLAd4O44ulcqngYfvM0WQAhmNb3m4Rg8wKaaN8vaOL3eSXrFX922qgTR8fgepCGm4IQhqmqJ3b4B_9gn7CJf8YN11ZO9yT0e6II91r9ifQ_zBvZZ6t3krfbAxUbcxhHn0evwIc6z8fDbb0FGlWIW9OGyL1UgbzRxRFTzJdQIDAQAB";
        String gtPrivateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJvdAqMsB3g7ji6VyqeBh-8zRZACGY1vebhGDzAppo3y9o4vd5JesVf3baqBNHx-B6kIabghCGqaondvgH_2CfsIl_xg3XVk73JPR7ogj3Wv2J9D_MG9lnq3eSt9sDFRtzGEefR6_AhzrPx8NtvQUaVYhb04bIvVSBvNHFEVPMl1AgMBAAECgYAHLNh3PIqnfU5hVKH8rhjc6SZVp9MXUL9wvUDrva8eL8Yr64F8qoFNhGV3CPWqmX6uyGVdhZ_GkJHUH7zxpxj0dAKl8XFrgV1I6YocQevrwvM6AYVf2U7XCOK_WR-sv3TBzceOFbZ1s7cWbqvkGypSURlpBJjBm9_db4Teqg_ZQQJBAN8qnOCwUtslPJWiG8tLoG2nsvfGmrR9oTnhk8N64L7KR2HlML4Efv-qhqCCZShp3V-TeRBX-NtqFBj6cvnyjlECQQCyy3p53c1dWFB3-BzCtaWq0LQ7Syod_0enBMcrvSyrkx5b03trzT7EoyiT-iVyfzOzDRHWpCCKleEQK91ZRgvlAkAIAk9_ANT4aG20MQ0uTpiDVvFlUwtaTufqW94htdc7AaduK_uD1kV4h3YtbICU4re_JlvB6mZT-YqfGt3len8BAkB2qTLMxJbyV5V4OZOk6fdcSY0EORtnsy_zuekRr0iBSm-Ak_e6kQoSaRKaOw81URSXxZnMMTtjnpszJ1mNUT69AkEArGAu0Srjirjz9f1wIQTfAjMQU0rEhzVX9HVXnlL8s0idUBBhEMSBCcrGssN06UpCUuKuM7nxT33se3zh-WC2Vg";
//        邮刊的公私钥
        String ykPublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCMIMRwGT8CuKqycwn_O6q9N4CE4tRuDaAlCNIS-cpvQ9dwb-q58ubXstyeVa1cJsBEEbl2qDBQDda-iegJgmmJY00U948A5qWf_LSQrxvPliWa1M_TOWLH1Cnjsle0tm3w-0Bo4ChzEJIdXImrFkM4jIxukfplaQ3sMe9mWbxDuwIDAQAB";
        String ykPrivateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIwgxHAZPwK4qrJzCf87qr03gITi1G4NoCUI0hL5ym9D13Bv6rny5tey3J5VrVwmwEQRuXaoMFAN1r6J6AmCaYljTRT3jwDmpZ_8tJCvG8-WJZrUz9M5YsfUKeOyV7S2bfD7QGjgKHMQkh1ciasWQziMjG6R-mVpDewx72ZZvEO7AgMBAAECgYBvpdf-HQ9oYqyW3DP16ZuDgYpj1rs9KJwVhe6jceUKO_qWuoVCPTgSWo-PlGI5TyLX2Wt1EFLWJgCY9hYsJX1h6tVYulSu0GBz0YAMKF4q2YONpwBe9YmI-o4gwJpHpuB6ZIdce4MB3CAd6txLphGsnoiKVXo7gD3vEQ7TjpUiuQJBANaAt5RLP0lWrYGWw2eDIx78dTsmOqv8lXCMnF2PpwyAhgNirpjQ754rBG78qKUSD3IfrNR-62FUDx-aZqHCnX8CQQCnPKCJHGH20G3lDsgsjAshtgXVXc-6Ewf8ZibvnaO7bdr1bQLyJsyaZLvuJx2t54tcR-oN5u_w0uKQBV4Y0W_FAkEAptCtdBdc3VUaVDiCOIMEkjl1lg1x_YTOVxwTErQADrn4_rME43VBlDkSFppJMS6tcmxtxUf7F9L-e-5guJYYUwJAWhnq8BQvn5dqLefJ515IPRBhkjQpz7mjKtQqlBydc0TbnDDwTmCjCWfObJ_8eI5wYfaI3paWnWwxDqElsj9cdQJAC2f0Ilga6gZjRPqHt668jStpX4Zj3b3ap_9nAcT7cwRjhmbX03QU8zfKEXw2MsDzibFwLrQSpd4yyn7kTD_OOw";

        String encodedData = TimeRSAUtils.publicEncrypt(str, TimeRSAUtils.getPublicKey(ykPublicKey));
        System.out.println("国通给邮刊的密文：\r\n" + encodedData);
        String decodedData = TimeRSAUtils.privateDecrypt(encodedData, TimeRSAUtils.getPrivateKey(ykPrivateKey));
        System.out.println("邮刊解密后文字: \r\n" + decodedData);

        str = "nice";
        encodedData = TimeRSAUtils.publicEncrypt(str, TimeRSAUtils.getPublicKey(gtPublicKey));
        System.out.println("邮刊给国通的密文：\r\n" + encodedData);
        decodedData = TimeRSAUtils.privateDecrypt(encodedData, TimeRSAUtils.getPrivateKey(gtPrivateKey));
        System.out.println("国通解密后文字: \r\n" + decodedData);
    }
}
